﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Dominio
{
    public class Context
    {
        //private Empresa empresa;
        private DataSet ds;
        private SqlCommand command;
        private static SqlConnection conn;
        private SqlDataAdapter adapter;
        private int lastCodigo;
        private static string connectionString = System.Configuration.ConfigurationSettings.AppSettings["DexConnectionString"];
        
        public  Context() 
        {
            if (connectionString != null)
            {
                conn = new SqlConnection(connectionString);
                conn.Open();
            }
        }

        public string getConnectionString()
        {
            return connectionString;
        }

        public DataSet SelectAll(string table, string spName)
        {
            try
            {
                command = new SqlCommand(spName, conn);
                command.CommandType = CommandType.StoredProcedure;
                adapter = new SqlDataAdapter(command);
                //adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;

                ds = new DataSet();
                adapter.Fill(ds, table);
            }
            catch (Exception ex)
            {

            }

            return ds;
        }

        public void Insert(string spName, Object obj)
        {
            Type ObjectType = obj.GetType();
            PropertyInfo[] properties = ObjectType.GetProperties();

            command = new SqlCommand(spName, conn);
            command.CommandType = CommandType.StoredProcedure;

            if (spName == "spAdicionarPessoa")
            {
                foreach (PropertyInfo propriedade in properties)
                {
                    if (!propriedade.Name.Equals("Codigo"))
                    {
                        Console.WriteLine(propriedade.Name);
                        if (!propriedade.Name.Equals("Observacao"))
                        {
                            command.Parameters.AddWithValue("@" + propriedade.Name, propriedade.GetValue(obj));
                        }
                    }
                }
            }

        }
    }
}
